﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.ComponentModel.Composition;

namespace Steve.UI.Extensions
{
    [Export(typeof(ILoggingService))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public sealed class TraceSourceLoggingService : ILoggingService
    {
        Dictionary<string, TraceSource> _sources = new Dictionary<string, TraceSource>();

        private TraceSource GetSource(string source)
        {
            //TODO: locking...
            if (_sources.ContainsKey(source)) return _sources[source];

            //move this source level default to config or something...
            var newSource = new TraceSource(source, SourceLevels.Off);

            _sources[source] = newSource;

            return newSource;
        }

        public void LogEvent(LogEventType type, string source, int id, string message, Exception exceptionInfo)
        {
            var trace = GetSource(source);
            var mapped = Map(type);

            //TODO: special handling of exception instance, TraceData?...
            trace.TraceEvent(mapped, id, message);

            if (exceptionInfo != null) trace.TraceData(mapped, id, exceptionInfo);
        }

        private static TraceEventType Map(LogEventType type)
        {
            switch(type)
            {
                case LogEventType.Critical:
                    return TraceEventType.Critical;
                case LogEventType.Error:
                    return TraceEventType.Error;
                case LogEventType.Warn:
                    return TraceEventType.Warning;
                case LogEventType.Info:
                    return TraceEventType.Information;
            }

            throw new ArgumentOutOfRangeException("type");
        }
    }
}
